import urllib.request
import re
import requests



def youdaoURLlib(Word):
        print("-"*20+'执行urllib方式'+"-"*20)
        #导入url信息
        url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

        data={'i':Word,
    'from':'AUTO',
    'to':'AUTO',
    'smartresult':'dict',
    'client':'fanyideskweb',
    'doctype':'json',
    'version':'2.1',
    'keyfrom':'fanyi.web',
    'action':'FY_BY_REALTIME',
    'typoResult':'false'}

        data = urllib.parse.urlencode(data).encode('utf-8')

        req = urllib.request.Request(url,data)
        
        res = urllib.request.urlopen(req)
        
        html = res.read().decode('utf-8')
        
        target='"tgt":"(.*?)"'

        The_Word = re.findall(target,html)
        
        print("翻译的结果为： %s" %(The_Word[0]))


def youdaoRequests(Word):
        print("-"*20+'执行Requests方式'+"-"*20)
        
        url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

        data={'i':Word,
    'from':'AUTO',
    'to':'AUTO',
    'smartresult':'dict',
    'client':'fanyideskweb',
    'doctype':'json',
    'version':'2.1',
    'keyfrom':'fanyi.web',
    'action':'FY_BY_REALTIME',
    'typoResult':'false'}
        
        res = requests.get(url,data)
        
        html = res.content.decode('utf-8')

        target='"tgt":"(.*?)"'

        The_Word = re.findall(target,html)
        
        print("翻译的结果为： %s" %(The_Word[0]))

if __name__ == '__main__':
	while True:
		Word = input("请输入翻译的词语(或输入q退出)：")
		if Word == "q":
			break
		m = input('请输入实现方式(1:urllib，2：requests）：')
		if m == "1":
			youdaoURLlib(Word)
		elif m == "2":
			youdaoRequests(Word)
		else:
			print('非预设方式，请重新输入')
